# python -m project_root.api.api_history
from .api_token import Token 
import requests

class Api_History(Token):

    def extract_sorted_values(self,data):
        # 提取所有 Temp 和 Humid 的键值对
        temp_items = {k: v for k, v in data.items() if k.startswith("Temp")}
        humid_items = {k: v for k, v in data.items() if k.startswith("Humid")}

        # 按数字排序 Temp 和 Humid
        sorted_temp = sorted(temp_items.items(), key=lambda x: int(x[0][4:]))  # "Temp1" -> 提取 1
        sorted_humid = sorted(humid_items.items(), key=lambda x: int(x[0][5:]))  # "Humid1" -> 提取 1

        # 提取排序后的值
        temp_values = [v for k, v in sorted_temp]
        humid_values = [v for k, v in sorted_humid]

        # 合并 Temp 和 Humid 的值
        combined_values = temp_values + humid_values

        return combined_values

    def get_history(self,start,end,parameter='time'):
        url = 'http://hxzhan.rtcloud.com:32111/tm/data/history'
        json = {
            'device_id':57714,
            'end':end,
            'limit':5,
            'page':1,
            'start':start
        }
        response = requests.post(url=url,json=json,headers=self.get_header())
        data = response.json()['data']['list']
        values = []
        datavalues = []
        if parameter == 'time':
            for n in data:
                values.append(n['CollectTime'])
            return values
        elif parameter == 'data':
            for n in data:
                values.append(self.extract_sorted_values(n))
            for v in values:
                datavalues += v
            return datavalues

# ap = Api_History()
# print(ap.get_history(1748707200000,1751299199000,'data'))